package user

import (
	"API/client"
	"API/request"
	"API/response"
	"common/global"
	"common/pkg"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	user "user_server/proto"
)

func RegisterHandler(c *gin.Context) {
	// 参数绑定与验证
	var req request.RegisterUserRequest
	if err := c.ShouldBind(&req); err != nil {
		response.CurrencyErrResponse(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	// 调用gRPC服务
	res, err := client.UserRegister(context.Background(), &user.RegisterRequest{
		Tel:      req.Tel,
		Password: req.Password,
	})

	if err != nil {
		response.CurrencyErrResponse(c, http.StatusInternalServerError, "服务调用失败: "+err.Error())
		return
	}

	// 处理注册结果
	if res.Success {
		response.CurrencySuccessResponse(c, "注册成功", gin.H{
			"user_id": res.Success,
		})
	} else {
		response.CurrencyErrResponse(c, http.StatusBadRequest, "注册失败: ")
	}
}

func LoginHandler(c *gin.Context) {
	// 参数校验
	var req request.LoginUserRequest
	if err := c.ShouldBind(&req); err != nil {
		response.CurrencyErrResponse(c, http.StatusBadRequest, "参数错误: "+err.Error())
		return
	}

	// 调用gRPC服务
	res, err := client.UserLogin(context.Background(), &user.LoginRequest{
		Tel:      req.Tel,
		Password: req.Passwd,
	})

	if err != nil {
		response.CurrencyErrResponse(c, http.StatusUnauthorized, "登录失败: "+err.Error())
		return
	}
	claims := pkg.CustomClaims{
		ID: uint(res.UserId),
	}
	fmt.Println(res.UserId)
	token, err := pkg.NewJWT(global.JwtSecretKey).CreateToken(claims)
	if err != nil {
		return
	}
	// 返回登录信息
	response.CurrencySuccessResponse(c, "登录成功", map[string]interface{}{
		"token": token,
	})
}
